package com.lz.springboot.apollo.config;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.lz.springboot.apollo.Application;

@Component
@EnableApolloConfig({"application"})
public class ApolloConfigApplication {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
	
	@ApolloConfig("application")
	private Config config; 

	@Value("${info.version:1.0.0}") 
	private String infoVersion;

	@ApolloConfigChangeListener("application")
	private void anotherOnChange(ConfigChangeEvent changeEvent) {
		Set<String> configNames = config.getPropertyNames();
		for(String configName : configNames) {
			LOGGER.info("configName=[{}] configValue=[{}]", configName, config.getProperty(configName, ""));
		}
		
		if (changeEvent.isChanged("test")) {
			ConfigChange change = changeEvent.getChange("test");
			LOGGER.info("Found change - key: {}, oldValue: {}, newValue: {}, changeType: {}",
					change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType());
		}
		
		if (changeEvent.isChanged("info.version")) {
			ConfigChange change = changeEvent.getChange("info.version");
			if(change != null){
				LOGGER.info("Found change - key: {}, oldValue: {}, newValue: {}, changeType: {}",
						change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType());
			}
		}
		
	}
	
	@Override
	public String toString() {
		return "ApplicationConfig [infoVersion=" + infoVersion + "]";
	}
	
}